package com.ydd.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ydd.constant.MessageConstant;
import com.ydd.constant.StatusConstant;
import com.ydd.dto.UserDTO;
import com.ydd.entity.*;
import com.ydd.mapper.*;
import com.ydd.result.Result;
import com.ydd.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ydd.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-05-15
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {
    @Autowired
    private YddAdvposServiceImpl advposService;
    @Autowired
    private YddTagServiceImpl tagService;
    @Autowired
    private YddArticleServiceImpl articleService;
    @Autowired
    private YddCateServiceImpl cateService;
    @Autowired
    private YddAdvimgServiceImpl advimgService;
    @Autowired
    private YddUserServiceImpl yddUserService;
    @Autowired
    private YddCateServiceImpl yddCateService;
    @Autowired
    private YddUserMapper userMapper;
    @Autowired
    private YddArticleMapper articleMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysRoleMapper roleMapper;
    @Autowired
    private SysRoleMapperMB roleMapperMB;

    @Override
    public Result baseInfo() {
//        BaseInfoVO vo = new BaseInfoVO();
//        long advposNum = advposService.count();
        long tagNum = tagService.count();
        long adminNum = this.count();
        long articleNum = articleService.count();
        long cateNum = cateService.count();
//        long advimgNum = advimgService.count();
        QueryWrapper<YddUser> wrapper = new QueryWrapper<>();
        wrapper.eq("sex",0);

        UserCount userCountn = UserCount.builder()
                .total(yddUserService.count())
                .userMan(yddUserService.count(wrapper))
                .build();
        userCountn.setUserWoman(userCountn.getTotal() - userCountn.getUserMan());
        List<YddCate> cates = yddCateService.list();
        List<CateVO> CateVOs = new ArrayList<>();
        cates.forEach(yddCate -> {
            CateVO cateVO = new CateVO();
            BeanUtils.copyProperties(yddCate, cateVO);

            if (cateVO.getId() != null) {
                Integer count = articleMapper.countByCatename(cateVO.getId());
                cateVO.setNum(count);
            }

            CateVOs.add(cateVO);
        });

        List<NewUser> newUserList = userMapper.getNewUser();
        List<HotArticleVO> hotArticlelist = articleMapper.getHotArticleList();
        BaseInfoVO vo = BaseInfoVO.builder()
                .adminNum(adminNum)
//                .advimgNum(advimgNum)
//                .advposNum(advposNum)
                .user(userCountn)
                .articleNum(articleNum)
                .newUserList(newUserList)
                .cateNum(cateNum)
                .cate(CateVOs)
                .tagNum(tagNum)
                .hotArticlelist(hotArticlelist)
                .build();

        return Result.success(vo);
    }

    @Override
    public Result UserList(UserDTO dto) {

        PageHelper.startPage(dto.getPage(), dto.getLimit());
        Page<UserInfo> page = sysUserMapper.userList(dto);
        for (UserInfo userInfo : page) {
            List<String> roles = JSON.parseArray(userInfo.getRoleId(), String.class);
            List<SysRole> role = roleMapperMB.getByIds(roles);
            List<String> roleNames = role.stream().map(sysRole -> sysRole.getName()).collect(Collectors.toList());
            userInfo.setRolename(roleNames);
        }
        PageVO vo = PageVO.builder()
                .data(page.getResult())
                .pageSize(dto.getLimit())
                .currentPage(dto.getPage())
                .count(page.getTotal())
                .build();

        return Result.success(vo);
    }

    @Override
    public Result delUser(String id) {
        if (id == null || id.equals("")) {
            return Result.error(MessageConstant.ID_NOT_FOUND);

        }
        this.removeById(id);
        return Result.success();
    }

    @Override
    public Result addUser(UserDTO dto) {
        if (dto.getName() == null || dto.getLogin_name() == null || dto.getPassword() == null) {
            return Result.error("用户名,密码和姓名不能为空");
        }
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("login_name", dto.getLogin_name());
        SysUser sysUser = this.getOne(wrapper);
        if (sysUser != null) {
            return Result.error("用户名重复");
        }
        SysUser user = SysUser.builder()
                .name(dto.getName())
                .loginName(dto.getLogin_name())
                .password(dto.getPassword())
                .build();
        if (dto.getEmail() != null) {
            user.setEmail(dto.getEmail());
        }
        List roleId = dto.getRoleId();
        if (roleId != null && roleId.size() != 0) {
            user.setRoleId(JSON.toJSONString(roleId));
        }
        if (dto.getPhone() != null) {
            user.setPhone(dto.getPhone());
        }
        if (dto.getStatus() == null) {
            user.setStatus(StatusConstant.DISABLE);
        }
        user.setStatus(dto.getStatus());
        this.save(user);
        return Result.success();
    }

    @Override
    public Result rowInfo(String id) {
        SysUser sysUser = this.getById(id);
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(sysUser, userInfo);
        String roleId = sysUser.getRoleId();
        if (roleId != null) {
            userInfo.setRole_id(JSON.parseArray(roleId, String.class));
        }
        return Result.success(userInfo);
    }

    @Override
    public Result updateUser(UserDTO dto) {
        if (dto.getId() == null) {
            return Result.error(MessageConstant.ID_NOT_FOUND);
        }
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(dto, sysUser);
        sysUser.setRoleId(JSON.toJSONString(dto.getRoleId()));
        this.updateById(sysUser);
        return Result.success();
    }
}
